package com.example.neutonote2.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.util.Log;

import androidx.security.crypto.EncryptedSharedPreferences;
import androidx.security.crypto.MasterKey;

import com.example.neutonote2.api.DeepseekApiClient;
import com.example.neutonote2.data.model.Note;
import com.example.neutonote2.data.model.NoteWithTags;
import com.example.neutonote2.data.model.Tag;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * DeepSeek工具类，提供方便的访问API的方法
 */
public class DeepseekUtils {
    private static final String TAG = "DeepseekUtils";
    private static final String PREF_NAME = "deepseek_prefs";
    private static final String ENCRYPTED_PREF_NAME = "deepseek_encrypted_prefs";
    private static final String KEY_API_KEY = "api_key";
    private static final ExecutorService executor = Executors.newSingleThreadExecutor();
    private static final Handler mainHandler = new Handler(Looper.getMainLooper());

    /**
     * 获取SharedPreferences实例，优先使用加密的实现
     */
    private static SharedPreferences getPreferences(Context context) {
        if (context == null) {
            Log.e(TAG, "获取Preferences失败：上下文为null");
            return null;

        }
        
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // 创建或获取主密钥
                MasterKey masterKey = new MasterKey.Builder(context)
                        .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
                        .build();
                
                // 创建加密的SharedPreferences
                return EncryptedSharedPreferences.create(
                        context,
                        ENCRYPTED_PREF_NAME,
                        masterKey,
                        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
                        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
                );
            } else {
                return context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
            }
        } catch (Exception e) {
            Log.e(TAG, "创建加密SharedPreferences失败：" + e.getMessage(), e);
            // 出错时回退到普通SharedPreferences
            return context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        }
    }

    /**
     * 保存API密钥到SharedPreferences（优先使用加密存储）
     */
    public static void saveApiKey(Context context, String apiKey) {
        if (context == null) {
            Log.e(TAG, "保存API密钥失败：上下文为null");
            return;
        }
        
        SharedPreferences prefs = getPreferences(context);
        if (prefs == null) {
            Log.e(TAG, "保存API密钥失败：无法获取Preferences");
            return;
        }
        
        prefs.edit().putString(KEY_API_KEY, apiKey).apply();
        Log.d(TAG, "API密钥已保存");
    }

    /**
     * 从SharedPreferences获取API密钥（优先尝试从加密存储获取）
     */
    public static String getApiKey(Context context) {
        if (context == null) {
            Log.e(TAG, "获取API密钥失败：上下文为null");
            return "";
        }
        
        SharedPreferences prefs = getPreferences(context);
        if (prefs == null) {
            Log.e(TAG, "获取API密钥失败：无法获取Preferences");
            return "";
        }
        
        String apiKey = prefs.getString(KEY_API_KEY, "");
        // 不要在日志中显示API密钥内容，只显示是否设置了密钥
        Log.d(TAG, "API密钥状态：" + (apiKey.isEmpty() ? "未设置" : "已设置"));
        return apiKey;
    }

    /**
     * 检查是否已设置API密钥
     */
    public static boolean isApiKeySet(Context context) {
        String apiKey = getApiKey(context);
        boolean isSet = apiKey != null && !apiKey.isEmpty();
        Log.d(TAG, "API密钥设置状态: " + isSet);
        return isSet;
    }

    /**
     * 处理笔记内容（在后台线程执行）
     * @param context 上下文
     * @param note 笔记
     * @param prompt 提示词
     * @param useChat 是否使用chat API (true: chat/completions, false: beta/completions)
     * @param callback 回调
     */
    public static void processNoteAsync(final Context context, final NoteWithTags note, final String prompt, final boolean useChat, final ApiCallback<String> callback) {
        try {
            if (context == null) {
                Log.e(TAG, "处理笔记失败：上下文为null");
                if (callback != null) {
                    mainHandler.post(() -> callback.onFailure("上下文为null"));
                }
                return;
            }
            
            if (note == null) {
                Log.e(TAG, "处理笔记失败：笔记对象为null");
                if (callback != null) {
                    mainHandler.post(() -> callback.onFailure("笔记对象为null"));
                }
                return;
            }
            
            final String apiKey = getApiKey(context);
            if (apiKey.isEmpty()) {
                Log.e(TAG, "处理笔记失败：API密钥未设置");
                if (callback != null) {
                    mainHandler.post(() -> callback.onFailure("API密钥未设置，请在设置中配置您的DeepSeek API密钥"));
                }
                return;
            }

            Log.d(TAG, "开始处理笔记，prompt：" + prompt + "，使用" + (useChat ? "chat" : "beta") + "API");
            // 使用原子变量来确保回调只调用一次
            final boolean[] callbackInvoked = {false};
            
            executor.execute(() -> {
                OkHttpClient testClient = null;
                Response testResponse = null;
                
                try {
                    // 首先测试API可访问性（只做连接测试，不检查权限）
                    String testUrl = "https://api.deepseek.com";
                    testClient = new OkHttpClient.Builder()
                            .connectTimeout(5, TimeUnit.SECONDS)
                            .build();
                    Request testRequest = new Request.Builder()
                            .url(testUrl)
                            .head()
                            .build();
                    
                    Log.d(TAG, "执行API连接测试");
                    testResponse = testClient.newCall(testRequest).execute();
                    int statusCode = testResponse.code();
                    Log.d(TAG, "API连接测试状态码: " + statusCode);
                    
                    // 连接成功，继续处理
                    if (statusCode >= 200 && statusCode < 500) {
                        Log.d(TAG, "API连接测试通过，继续处理请求");
                        
                        // 关闭测试响应
                        if (testResponse != null) {
                            testResponse.close();
                            testResponse = null;
                        }
                        
                        // 执行实际API调用
                        DeepseekApiClient client = DeepseekApiClient.getInstance(apiKey);
                        String result = client.processNote(note, prompt, useChat);
                        Log.d(TAG, "笔记处理完成，结果长度：" + (result != null ? result.length() : 0));
                        
                        if (callback != null && !callbackInvoked[0]) {
                            callbackInvoked[0] = true;
                            mainHandler.post(() -> {
                                try {
                                    callback.onSuccess(result);
                                } catch (Exception e) {
                                    Log.e(TAG, "成功回调异常: " + e.getMessage(), e);
                                }
                            });
                        }
                    } else {
                        // 服务器错误，可能是API服务不可用
                        Log.e(TAG, "API服务器返回错误状态码: " + statusCode);
                        if (callback != null && !callbackInvoked[0]) {
                            callbackInvoked[0] = true;
                            mainHandler.post(() -> {
                                callback.onFailure("DeepSeek API服务器错误，状态码: " + statusCode);
                            });
                        }
                    }
                } catch (Exception e) {
                    Log.e(TAG, "笔记处理异常：" + e.getMessage(), e);
                    if (callback != null && !callbackInvoked[0]) {
                        callbackInvoked[0] = true;
                        mainHandler.post(() -> {
                            try {
                                String errorMessage = "处理失败: " + e.getMessage();
                                // 检查是否是网络错误
                                if (e instanceof java.net.UnknownHostException) {
                                    errorMessage = "网络错误：无法连接到DeepSeek API服务器，请检查网络连接";
                                } else if (e instanceof java.net.SocketTimeoutException) {
                                    errorMessage = "网络错误：连接超时，请稍后重试";
                                } else if (e instanceof javax.net.ssl.SSLHandshakeException) {
                                    errorMessage = "SSL错误：无法建立安全连接";
                                }
                                callback.onFailure(errorMessage);
                            } catch (Exception ex) {
                                Log.e(TAG, "错误回调异常: " + ex.getMessage(), ex);
                            }
                        });
                    }
                } finally {
                    // 确保响应资源被关闭
                    if (testResponse != null) {
                        try {
                            testResponse.close();
                        } catch (Exception e) {
                            Log.e(TAG, "关闭测试响应异常: " + e.getMessage(), e);
                        }
                    }
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "处理笔记意外异常：" + e.getMessage(), e);
            if (callback != null) {
                mainHandler.post(() -> {
                    try {
                        callback.onFailure("发生异常: " + e.getMessage());
                    } catch (Exception ex) {
                        Log.e(TAG, "错误回调异常: " + ex.getMessage(), ex);
                    }
                });
            }
        }
    }

    /**
     * 总结笔记内容（在后台线程执行）
     * @param context 上下文
     * @param content 笔记内容
     * @param callback 回调
     */
    public static void summarizeNoteAsync(Context context, String content, ApiCallback<String> callback) {
        try {
            if (context == null) {
                Log.e(TAG, "总结笔记失败：上下文为null");
                if (callback != null) {
                    mainHandler.post(() -> callback.onFailure("上下文为null"));
                }
                return;
            }
            
            if (content == null || content.trim().isEmpty()) {
                Log.e(TAG, "总结笔记失败：内容为空");
                if (callback != null) {
                    mainHandler.post(() -> callback.onFailure("内容为空"));
                }
                return;
            }
            
            String apiKey = getApiKey(context);
            if (apiKey.isEmpty()) {
                Log.e(TAG, "总结笔记失败：API密钥未设置");
                if (callback != null) {
                    mainHandler.post(() -> callback.onFailure("API密钥未设置，请在设置中配置您的DeepSeek API密钥"));
                }
                return;
            }

            Log.d(TAG, "开始总结笔记，内容长度：" + content.length() + "，使用beta API");
            executor.execute(() -> {
                try {
                    DeepseekApiClient client = DeepseekApiClient.getInstance(apiKey);
                    
                    // 创建一个临时NoteWithTags对象用于API调用
                    NoteWithTags noteWithTags = new NoteWithTags();
                    noteWithTags.note = new Note("临时标题", content, "临时分类");
                    
                    String summary = client.processNote(
                            noteWithTags, 
                            "请为以下笔记内容生成一个简洁的摘要（不超过200字）", 
                            false // 使用beta API
                    );
                    
                    Log.d(TAG, "笔记总结完成，结果长度：" + (summary != null ? summary.length() : 0));
                    if (callback != null) {
                        mainHandler.post(() -> callback.onSuccess(summary));
                    }
                } catch (Exception e) {
                    Log.e(TAG, "笔记总结异常：" + e.getMessage(), e);
                    if (callback != null) {
                        mainHandler.post(() -> callback.onFailure("摘要生成失败: " + e.getMessage()));
                    }
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "总结笔记意外异常：" + e.getMessage(), e);
            if (callback != null) {
                mainHandler.post(() -> callback.onFailure("发生异常: " + e.getMessage()));
            }
        }
    }

    /**
     * 获取API状态信息
     * @return API状态信息
     */
    public static String getApiStatus(Context context) {
        if (context == null) {
            return "未初始化";
        }
        
        String apiKey = getApiKey(context);
        if (apiKey.isEmpty()) {
            return "未配置API密钥";
        }
        
        if (apiKey.length() < 10) {
            return "API密钥无效";
        }
        
        return "DeepSeek API已配置 (" + apiKey.substring(0, 5) + "...)";
    }

    /**
     * API回调接口
     */
    public interface ApiCallback<T> {
        void onSuccess(T result);
        void onFailure(String error);
    }
} 